package com.lingtu.shopwxserver.utils;

import com.lingtu.shopwxserver.pojo.Image;
import com.lingtu.shopwxserver.pojo.ImageMessage;
import com.thoughtworks.xstream.XStream;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Random;

/**
 * @ClassName ImageMessageUtil
 * @Description 图片信息工具类
 * @Author MaShuai
 * @Date 2018/11/23 10:56
 * @Version 1.0
 **/
public class ImageMessageUtil implements BaseMessageUtil<ImageMessage> {

    /**
     * @Description 将信息转为xml格式
     * @Param [imageMessage]
     * @return java.lang.String
     */
    @Override
    public String messageToXml(ImageMessage imageMessage) {
        XStream xtream = new XStream();
        xtream.alias("xml", imageMessage.getClass());
        xtream.alias("Image", new Image().getClass());
        return xtream.toString();
    }

    /**
     * @Description 封装信息
     * @Param [fromUserName, toUserName]
     * @return java.lang.String
     */
    @Override
    public String initMessage(String fromUserName, String toUserName) {
        Image image = new Image();
        image.setMediaId(getMediaId());
        ImageMessage message = new ImageMessage();
        message.setFromUserName(toUserName);
        message.setToUserName(fromUserName);
        message.setCreateTime(System.currentTimeMillis());
        message.setImage(image);
        return messageToXml(message);
    }

    /**
     * @Description 获取Media
     * @Param []
     * @return java.lang.String
     */
    public String getMediaId(){
        //Random random = new Random();
        String path = "D:/image/1.jpg";
        System.out.println("路径："+path);
        String accessToken = WeiXinUtil.getAccessToken().getAccessToken();
        String mediaId = null;
        try {
            mediaId = UploadUtil.upload(path, accessToken, "image");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return mediaId;
    }




}
